package com.googlecode.latvian_ebooks.glossary;

import scala.util.matching.Regex
import scala.collection.mutable.HashSet
import java.io.File
import scala.io.Source

/**
 * Read the glossary 
 */
class GlossaryTerms() {

  @scala.reflect.BeanProperty
  var terms: List[FullTerm] = List.empty[FullTerm]

  def this(fileName: String) = {
    this()
    terms = parse(fileName)
  }

  /**
   * Read the "... {...} ..." file structure
   */
  def parse(fName: String): List[FullTerm] = {
    val lines: List[String] = Source.fromFile(new File(fName)).getLines.toList
    val pattern = new Regex("""\s*(.*)\s*\{(.*)\}\s*(.*)\s*""", "fr", "segments", "lv")
    val result = for (line <- lines) yield {
      pattern.findFirstIn(line) match {
        case Some(name) => {
          val result = pattern.findFirstMatchIn(line).get;
          new FullTerm(result.group("fr"), result.group("segments"), result.group("lv"))
        }
        case None => {
          println("No name value for line " + line)
          System.exit(0)
          null
        }
      }
    }
    println ("returning " + result.size + " pieces")
    result
  }
  

  def findDuplicates() {
	println("Finding duplicates among " + terms.size + " terms...")
    var previousTerm = ""
    var previousTerms: HashSet[String] = new HashSet[String]
    var i = 0
    var dc = 0
    for (term <- terms) {
      i = i + 1
      val lcTerm = term.getTerm.toLowerCase
      if (!lcTerm.equals(previousTerm) && previousTerms.contains(lcTerm)) {
        println("Duplicate: " + lcTerm + "(line " + i + ")")
        dc = dc + 1
      }
      previousTerms.add(lcTerm)
      previousTerm = lcTerm
    }
    if (dc == 0) {
      println("No duplicates found")
    } else {
    	println("" + dc + " duplicates found")
    }
  }

  override def toString(): String = {
    var result = new StringBuilder
    for (term <- terms) {
      result.append("<term fr='" + term.getTerm.trim + "' loc='" + term.getLocations.mkString(",") + "' ")
      result.append("lv='" + term.getTranslation.trim + "'>\n<sort>" + term.getTerm.trim + "</sort></term>")
      val fragmentList: List[Int] = FileSearchUtility.getLocationFragments(term.getLocations)
//      result.append(" [" + fragmentList.mkString(",") + "]")
      result.append('\n')
    }
    result.toString
  }

//  def curlyFragmentList(fragmentList: List[Int]): String = {
//    var result = fragmentList.foldLeft("")((a, b) => a + "," + b)
//    result = "{" + result.substring(1, result.length() - 1) + "}";
//    result = result.replaceAll(" ", "");
//    return result;
//  }

}
